package com.imu.purse.modules.trade.service.impl;

import com.github.pagehelper.PageHelper;
import com.imu.common.exception.ErrorDesc;
import com.imu.common.exception.RRException;
import com.imu.constant.Constant;
import com.imu.core.base.BaseService;
import com.imu.core.redisplus.annotation.RedisLock;
import com.imu.enums.OrderTypeStatus;
import com.imu.enums.PStatus;
import com.imu.enums.TradeType;
import com.imu.purse.modules.base.entity.SysConfigEntity;
import com.imu.purse.modules.trade.dao.YmbWithdrawMapper;
import com.imu.purse.modules.trade.entity.FundEntity;
import com.imu.purse.modules.trade.entity.TradeInfoEntity;
import com.imu.purse.modules.trade.entity.YmbWithdrawEntity;
import com.imu.purse.modules.trade.service.FundService;
import com.imu.purse.modules.trade.service.TradeInfoService;
import com.imu.purse.modules.trade.service.YmbWithdrawService;
import com.imu.utils.DateUtil;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.xiaoleilu.hutool.util.NumberUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 易买宝充值详情表
 * @author sunhongwei
 * @email sunhongwei@jshijian.com
 * @date 2018-07-02 23:47:18
 * Copyright (c) 2017 武汉极时间科技有限公司 版权所有 
 * Jshijian aloha CO.,LTD. All Rights Reserved. 
 */
@Service
public class YmbWithdrawServiceImpl extends BaseService<YmbWithdrawEntity> implements YmbWithdrawService
{
	@Override
    @Transactional
    public int save(final YmbWithdrawEntity entity)
	{
		entity.setOrderState(PStatus.Create.getType());
		entity.setCreateTime(System.currentTimeMillis());
		entity.setUpdateTime(System.currentTimeMillis());
    	return super.insert(entity);
	}
	
	@Override
	@Transactional
    public int update(final YmbWithdrawEntity entity) 
    {
    	entity.setUpdateTime(System.currentTimeMillis());
    	return mapper.updateByPrimaryKeySelective(entity);
    }
    
    @Override
	@Transactional
    public int saveUpdate(final YmbWithdrawEntity entity)
    {
    	int len = 0;
    	
    	if(1 > (len = this.update(entity)))
    	{
        	len = this.insert(entity);
    	}
    	
    	return len;
    }
    
 	@Override
	@Transactional
    public boolean delete(final String ...ids)
    {
    	if(ArrayUtil.isEmpty(ids)) return false;
    	
    	for (String id : ids) 
    	{
    		if(StrUtil.isBlank(id)) continue;
    		
    		if(NumberUtil.isNumber(id))
    		{
        		mapper.deleteByPrimaryKey(Long.valueOf(id));
    		}
		}
    	
    	return true;
    }
 	
 	@Override
	@Transactional
	@RedisLock(keys = "#key", expire = 30000, tryTimeout = 1000)
 	public void withdraw(final String key, final YmbWithdrawEntity dto)
 	{
 		//验证用户余额信息 是否支持本次私募
        FundEntity fund = fundService.findByUserId(dto.getUserId());
        if(null == fund) {
        	throw new RRException(ErrorDesc.GET_USER_ERR.getMsg(), ErrorDesc.GET_USER_ERR.getCode());
        }
        else if(null == fund.getBj() || fund.getBj().compareTo(dto.getBjNum()) < 0) {
        	throw new RRException(ErrorDesc.YMB_LESS_THAN.getMsg(), ErrorDesc.YMB_LESS_THAN.getCode());
        }
        
        //是否有未处理中的单子
        YmbWithdrawEntity query = new YmbWithdrawEntity();
        query.setUserId(dto.getUserId());
        query.setStime(DateUtil.setStartDay(new Date()).getTime());
        query.setEtime(DateUtil.setEndDay(new Date()).getTime());
        
        if(null != mapper.find(query)) {
        	throw new RRException(ErrorDesc.WITHDRAW_ERROR.getMsg(), ErrorDesc.WITHDRAW_ERROR.getCode());
        }
        
        //保存提现信息
        this.save(dto);
        
        //信息归集
        SysConfigEntity config = sysConfigService.findByKey(Constant.PRI_USER_KEY);
        Long userId = 0l;
        if(null != config && StrUtil.isNotBlank(config.getValue()))
        {
        	try {
				userId = Long.valueOf(config.getValue());
        	} 
        	catch (Exception e) { }
        }
        
        //扣减易买宝 保存流水记录
        TradeInfoEntity tradeEntity = new TradeInfoEntity();
        tradeEntity.setId(null);
        tradeEntity.setOrderNo(dto.getId().toString());
        tradeEntity.setPayUserId(dto.getUserId());
        tradeEntity.setRecUserId(userId);
        tradeEntity.setMoney(dto.getBjNum());
        tradeEntity.setSmoney(fund.getBj());
        tradeEntity.setEmoney(fund.getBj().subtract(dto.getBjNum()));
        tradeEntity.setOrderType(OrderTypeStatus.EXTRACT.getType());
        tradeEntity.setOrderState(PStatus.Finished.getType());
        tradeEntity.setYtfType(TradeType.YMB.getType());
        tradeInfoService.save(tradeEntity);
        //扣减易买宝
        FundEntity fundEntity = new FundEntity();
        fundEntity.setUserId(dto.getUserId());
        fundEntity.setMoney(dto.getBjNum().multiply(new BigDecimal(-1)));
        fundEntity.setYtfType(TradeType.YMB.getType());
        fundService.updateMoneyByUIdAndYtype(fundEntity);
        //信息归集
        if(userId > 0) {
        	fund = fundService.findByUserId(userId);
        	
        	if(null != fund)
        	{
        		//增加GET 保存流水记录
    	        tradeEntity.setId(null);
    	        tradeEntity.setOrderNo(dto.getId().toString());
    	        tradeEntity.setPayUserId(userId);
    	        tradeEntity.setRecUserId(dto.getUserId());
    	        tradeEntity.setMoney(dto.getBjNum());
    	        tradeEntity.setSmoney(fund.getBj());
    	        tradeEntity.setEmoney(fund.getBj().add(dto.getBjNum()));
    	        tradeEntity.setOrderType(OrderTypeStatus.IN.getType());
    	        tradeEntity.setYtfType(TradeType.YMB.getType());
    	        tradeInfoService.save(tradeEntity);
    	        
    	        fundEntity = new FundEntity();
    			fundEntity.setUserId(userId.longValue());
    	        fundEntity.setMoney(dto.getBjNum());
    	        fundEntity.setYtfType(TradeType.YMB.getType());
    			fundService.updateMoneyByUIdAndYtype(fundEntity);
        	}
        }
 	}
    
    @Override
    public YmbWithdrawEntity findById(final Long id)
    {
    	if(null == id) return null;
    	return mapper.selectByPrimaryKey(id);
    }
    
    @Override
    public List<YmbWithdrawEntity> queryList(final YmbWithdrawEntity entity)
    {
    	if (entity.getPage() != null && entity.getLimit() != null)
    	{
            PageHelper.startPage(entity.getPage(), entity.getLimit());
        }
    	
    	return mapper.findByPage(entity);
    }
    

	@Autowired
	private FundService fundService;
	
	@Autowired
	private TradeInfoService tradeInfoService;
    
	@Autowired
	private YmbWithdrawMapper mapper;
	
    @Autowired
    private com.imu.purse.modules.base.service.SysConfigService sysConfigService;
}
